<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Test;
use Illuminate\Http\Request;
use App\Http\Requests;

header("Content-Type: application/xml");

const COMPORGCODE = 'YZSM';
const KEY = 'wxd9c866ad31c3c6wxd9c866ad31c3c6';

class RebackController extends Controller {
    
    public function lakalaback(){
        $reqxml = file_get_contents("php://input");
//        dd($reqxml);
        $request = simplexml_load_string($reqxml);
        $content = json_encode($request);
        $test = New Test;
        $test->content = $content;
        $test->type = 'lakala';
        $test->addtime = date('Y-m-d H:i:s');
        $test->save(); 
        $arr = json_decode($content, TRUE);
        $data = $this->_unsetNull($arr);
//        dd($data);
        $ret = $toxml = array();
        $mac = sha1($data['responseCode'].$data['compOrgCode'].$data['reqLogNo'].$data['ornReqLogNo'].$data['reqTm'].$data['payChlTyp'].$data['mercId'].$data['txnAmt'].
                $data['txnTm'].$data['tradeType'].$data['sub_appid'].$data['payOrderId'].$data['merOrderNo'].KEY);
        if($mac == $data['MAC']){
            $ret['RetCode'] = '00';
            $ret['extRpData'] = '';
            $ret['RetMsg'] = 'OK';
            $ret['MAC'] = sha1($ret['RetCode'].KEY);
            $toxml = "<?xml version='1.0' encoding='GBK'?><ROOT>{$this->arrayToXMLString($ret)}</ROOT>";
        }
        else{
            $ret['RetCode'] = '11';
            $ret['extRpData'] = $mac;
            $ret['RetMsg'] = '验签失败';
            $ret['MAC'] = sha1($ret['RetCode'].KEY);
            $toxml = "<?xml version='1.0' encoding='GBK'?><ROOT>".$this->arrayToXMLString($ret)."</ROOT>";
            $toxml=iconv("UTF-8", "GBK", $toxml);
        }
        echo $toxml;
    }
    
    public function baifuback(Request $request){
        $data = $request->json()->all();
        $data = iconv('GBK', 'UTF-8', $data);
        $test = New Test;
        $test->content = json_encode($data);
        $test->type = 'baifu';
        $test->addtime = date('Y-m-d H:i:s');
        $test->save(); 
        $ret = array(
            'respCode'  => '00000',
            'respInfo'  => '交易成功'
        );
        if($data['respCode']!='00000'){
            $ret['respCode'] = $data['respCode'];
            $ret['respInfo'] = $data['respInfo'];
            return json_encode($ret);
        }
        $signature = $data['signature'];
        $data['signature'] = "@eidpay";
        $sign = $this->sign(json_encode($data));
//        echo $signature."<br/>";
//        echo $sign;exit;
        if($sign!=$signature){
            $ret['respCode'] = '20000';
            $ret['respInfo'] = '交易异常';
            return json_encode($ret);
        }
        return json_encode($ret);
    }
    
//    public function baifuback4Single(Request $request){
//        $key_file = "E:/wamp64/www/yifutong/898000000020186_public.pem";
//        $data = $request->json()->all();
//        $sign = $this->juValidateSignature(json_encode($data),$key_file);  //签名;
//        if($sign==$data['signature']){
//            if($data['ordStatus']=='00000'){
//                echo 'ok';
//            }
//        }
//    }
    
    //百付代付通知(异步)
    public function baifuback4Single(Request $request){
        $key_file = storage_path('key/898000000020186_public.pem');     //密钥
        $data = $request->json()->all();
        $test = New Test;
        $test->content = json_encode($data);
        $test->type = 'baifu';
        $test->addtime = date('Y-m-d H:i:s');
        $test->save(); 
        $ret = array(
            'respCode'  => '00000',
            'respInfo'  => '交易成功'
        );
        if($data['ordStatus']!='00000'){
            $ret['respCode'] = $data['ordStatus'];
            $ret['respInfo'] = $data['ordInfo'];
            return json_encode($ret);
        }
        $signature = $data['signature'];
        $data['signature'] = "@eidpay";
        $sign = $this->juSignature(json_encode($data), $key_file);
        if($sign!=$signature){
            $ret['respCode'] = '20000';
            $ret['respInfo'] = '交易异常';
            return json_encode($ret);
        }
        echo 'ok';
    }
    
    //百付签名
    private function sign($data) {
        $certs = array();
        openssl_pkcs12_read(file_get_contents(storage_path('key/999002100009999.pfx')), $certs, "123pay"); 
        if(!$certs) return ;
        $signature = '';  
        openssl_sign($data, $signature, $certs['pkey']);
        return base64_encode($signature); 
    }
    
    // 验签（商户接入需调用此接口）
    private function juValidateSignature($info, $key_file)
    {
        if ($info == null || $key_file == null)
        {
            return false;
        }
        if (! file_exists($key_file))
        {
            return false;
        }
        $nSignStart = stripos($info, '"signature":"');
        $nSignEnd = stripos($info, '"', $nSignStart+13);
        $strSigned = substr($info, $nSignStart+13, $nSignEnd-$nSignStart-13);
        $info = str_replace($strSigned, '@eidpay', $info);
        $strValidate = $this->juSignature($info, $key_file);
        return strcasecmp($strSigned, $strValidate) == 0;
    }
    
    // 签名（商户接入需调用此接口）
    private function juSignature($info, $key_file)
    {
        if ($info == null || $key_file == null)
        {
            return '';
        }

        if (! file_exists($key_file))
        {
            return '';
        }

        $strKeyData = '';
        $handle = @fopen($key_file, "r");
        if ($handle == null)
        {
            return '';
        }
        while (! feof($handle))
        {
            $strLine = fgets($handle, 8192);
            $strLine = trim($strLine);
            if ( $strLine == null || strlen($strLine) == 0 ||
                strpos($strLine, '--') !== false )
            {
                continue;
            }
            $strKeyData .= $strLine;
        }
        fclose($handle);

        return md5($strKeyData . $info);
    }
    
    //数组转xml字符串
    private function arrayToXMLString ($array) {
        $xmlString = "";

        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $xmlString .= "<$key>\n";
                $xmlString .= arrayToXMLString($value);
                $xmlString .= "</$key>\n";
            } else {
                $xmlString .= "<$key>";
                $xmlString .= "$value";
                $xmlString .= "</$key>\n";
            }
        }

        return $xmlString;
    }
    
    //把 null转换为空'' 递归方式
    private function _unsetNull($arr){
        if($arr !== null){
            if(is_array($arr)){
                if(!empty($arr)){
                    foreach($arr as $key => $value){
                        if($value === null){
                            $arr[$key] = '';
                        }else{
                            $arr[$key] = $this->_unsetNull($value);      //递归再去执行
                        }
                    }
                }else{ $arr = ''; }
            }else{
                if($arr === null){ $arr = ''; }         //注意三个等号
            }
        }else{ $arr = ''; }
        return $arr;
    }
        
}

